package com.qf.interceptor;

import com.alibaba.fastjson2.JSONObject;
import com.qf.utils.R;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.PrintWriter;

@Component
public class AuthInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session = request.getSession();
        Object user = session.getAttribute("user");
        if (user == null){ // 没有登录信息,不放行,还有返回错误信息

            // 设置响应格式为json
            response.setContentType("application/json;charset=utf-8");
            PrintWriter writer = response.getWriter();

            // 将R对象转换为json字符串,使用fastjson工具,需要导入依赖
            R r = new R();
            r.setCode(500);
            r.setMsg("没有登录,禁止访问");
            String jsonString = JSONObject.toJSONString(r);

            // 这个将字符串写出到浏览器
            writer.write(jsonString);

            return false;
        }
        return true; // 登录成功,放行
    }
}
